package freeboard;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.examples.HtmlToPlainText;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import noticeboard.Notice;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.util.Log;

import com.andro.chansung.ConstantName;
import com.andro.chansung.ConstantURL;
import com.andro.chansung.DB;

public class BoardUpdateThread extends Thread {
	private int pageNumber;
	private String url;
	
	private Context parentContext;
	private Handler handler;
	
	public BoardUpdateThread(String url, int pageNumber, Context parentContext, Handler handler) {
		this.url = url;
		this.pageNumber = pageNumber;
		this.parentContext = parentContext;
		this.handler = handler;
	}
	
	public void run() {
		try {
			Document doc 		= Jsoup.connect(url + pageNumber).get();
			Elements noticeTag	= doc.select("notice"); 
			
			SQLiteDatabase db = parentContext.openOrCreateDatabase(ConstantName.DATABASE_NAME, Context.MODE_WORLD_WRITEABLE, null);
			for( int i = 0; i < noticeTag.size(); i++ ) {
				Notice notice = new Notice(i, 
										   Integer.parseInt(noticeTag.get(i).select("number").text().replaceAll("\\s", "")), 
										   0, 
										   noticeTag.get(i).select("title").text(),
										   noticeTag.get(i).select("writer").text(),
										   noticeTag.get(i).select("date").text(),
										   noticeTag.get(i).select("imgSrc").text().substring(noticeTag.get(i).select("imgSrc").text().indexOf("_id=") + 4,
												   											  noticeTag.get(i).select("imgSrc").text().lastIndexOf("&")));
				if( url.equals(ConstantURL.FREE_BOARD_URL) ) {
					DB.insertDataIntoFreeTable(db, notice);
				} else if ( url.equals(ConstantURL.CAREER_BOARD_URL) ) {
					DB.insertDataIntoCareerTable(db, notice);
				} else {
					DB.insertDataIntoNoticeTable(db, notice);
				}
			}
			db.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);
	}
}